package com.js.jetpackdemo.activity

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.core.content.edit
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.js.jetpackdemo.databinding.ActivityMainBinding
import com.js.jetpackdemo.db.AppDatabase
import com.js.jetpackdemo.entity.User
import com.js.jetpackdemo.lifeCycle.MyObserver
import com.js.jetpackdemo.viewModel.MainViewModel
import com.js.jetpackdemo.viewModelFactory.MainViewModelFactory
import com.js.jetpackdemo.worker.SimpleWorker
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread


// Created by JS on 2021/5/26.

class MainActivity: BaseActivity<ActivityMainBinding>() {

    companion object {
        const val TAG = "MainActivity"
    }

    lateinit var viewModel : MainViewModel
    lateinit var sp: SharedPreferences
    private var count = 0


    override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(MyObserver(lifecycle))
        sp = getPreferences(Context.MODE_PRIVATE)
        val countReserved = sp.getInt("count_reserved", 0)
        viewModel = ViewModelProvider(this, MainViewModelFactory(countReserved)).get(MainViewModel::class.java);
        initView()
    }

    private fun initView() {
        binding.plusOneBtn.setOnClickListener{
            viewModel.plusOne()
            count ++
            Log.d("MyObserver", "current state : ${lifecycle.currentState}")
            refreshCounter()
        }
        binding.clearBtn.setOnClickListener{
            viewModel.clear()
            count = 0
            refreshCounter()
        }
        viewModel.counter.observe(this) { count ->
            binding.infoText.text = count.toString()
        }
        binding.getUserBtn.setOnClickListener{
            val userId = (0..10000).random().toString()
            viewModel.getUser(userId)
        }
        viewModel.user.observe(this, Observer { user ->
            binding.infoText.text = user.firstName
        })
        refreshCounter()


        val userDao = AppDatabase.getDatabase(this).userDao()
        val user1 = User("Tom", "Brady", 40)
        val user2 = User("Tom", "Hanks", 63)
        binding.addDataBtn.setOnClickListener{
            thread {
                user1.id = userDao.insertUser(user1)
                user2.id = userDao.insertUser(user2)
            }
        }
        binding.updateDataBtn.setOnClickListener {
            thread {
                user1.age = 42
                userDao.updateUser(user1)
            }
        }
        binding.deleteDataBtn.setOnClickListener {
            thread {
                userDao.deleteUserByLastName("Hanks")
            }
        }
        binding.queryDataBtn.setOnClickListener {
            thread {
                for (user in userDao.loadAllUsers()) {
                    Log.d(TAG, user.toString())
                }
            }
        }
        binding.doWorkBtn.setOnClickListener {
            val currentTime = System.currentTimeMillis()
            val timeString = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date(currentTime))
            Log.d("SimpleWorker", "current time：$timeString")
            val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
                .setInitialDelay(5, TimeUnit.SECONDS)
                .addTag("simple")
                .build()
            WorkManager.getInstance(this).enqueue(request)
        }
    }

    private fun refreshCounter() {
        binding.normalText.text = count.toString()
    }

    override fun onPause() {
        super.onPause()
        sp.edit {
            putInt("count_reserved", viewModel.counter.value ?: 0)
        }
    }

    fun test(): List<String>? {
        val list: MutableList<String> = ArrayList()
        list.add("apple")
        list.add("banana")
        return list
    }
}